//
//  KLSGBrifAndVoiceViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGBrifAndVoiceViewController.h"
#import "KLSGBrifView.h"
#import "KLSGTracksListCell.h"
#import "KLSGSpeakBrifController.h"
#import "PellTableViewSelect.h"
#import "KLSGDataFail.h"

@interface KLSGBrifAndVoiceViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) KLSGDataFail *fail;
@property (nonatomic, assign) NSInteger pageId;
@property (nonatomic, assign) NSInteger pageCount;
@property (nonatomic, strong) NSMutableArray *tempArray;

@property (nonatomic, strong) UIButton *footerButton;

@end

@implementation KLSGBrifAndVoiceViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addNavigationBar];
    [self addTableView];
    _pageId = 1;
    [self addData];
}

- (void)addNavigationBar
{
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(returnA)];
    self.navigationItem.leftBarButtonItem = left;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_collect"] forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(actionRight) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = right;
}

- (void)returnA
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)actionRight
{

    KLSGDB *dbManager = [[KLSGDB alloc] init];
    NSLog(@"%d", [self.model.albumId intValue]);
    if ([dbManager queryKindWithAlbumId:self.model.albumId]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alertVC animated:YES completion:nil];
        [self performSelector:@selector(dismissAlertVC:) withObject:alertVC afterDelay:0.5];
    } else {
        if ([dbManager insertWithKindModel:self.model]) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:alertVC animated:YES completion:nil];
            [self performSelector:@selector(dismissAlertVC:) withObject:alertVC afterDelay:0.5];
        } else {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏失败" preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:alertVC animated:YES completion:nil];
            [self performSelector:@selector(dismissAlertVC:) withObject:alertVC afterDelay:0.5];
        }
       
    }
}

- (void)dismissAlertVC:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
}

- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:(UITableViewStyleGrouped)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    self.tableView.bounces = NO;
    
    UIButton *footerButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    footerButton.frame = CGRectMake(0, 0, kScreenWidth, 50);
    [footerButton setTitle:@"点击加载更多" forState:(UIControlStateNormal)];
    [footerButton setTitleColor:[UIColor orangeColor] forState:(UIControlStateNormal)];
    [footerButton addTarget:self action:@selector(actionFooter:) forControlEvents:(UIControlEventTouchUpInside)];
    self.tableView.tableFooterView = footerButton;
    self.footerButton = footerButton;

    [self.view addSubview:self.tableView];
}

- (void)actionFooter:(UIButton *)button
{
    _pageId++;
    if (_pageId <= [self.tracksModel.maxPageId integerValue]) {
        [self addData];
    } else {
        [button setTitle:@"加载完毕" forState:(UIControlStateNormal)];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.lists.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    KLSGTracksListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[KLSGTracksListCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }

    NSArray *array = self.lists;
    // 防止越界
    if (array.count < indexPath.row) {
        return cell;
    }
    KLSGListModel *model = array[indexPath.row];
    cell.titleLale.text = model.title;
    CGFloat playTimes = [model.playtimes floatValue];
    cell.playTimesLale.text = [NSString stringWithFormat:@"%.1f万", playTimes / 1000];
    NSInteger time = [model.duration intValue];
    cell.timeLale.text = [NSString stringWithFormat:@"%02d:%02d", time / 60, time % 60];
    if ([self.tracksModel.totalCount integerValue] == self.lists.count && self.tracksModel.totalCount != 0 )
    {
        _footerButton.hidden = YES;
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    KLSGBrifView *brifView = [[KLSGBrifView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight / 4)];
    KLSGAlbumDetailModel *model = self.albumModel;
    NSLog(@"%@", model.coverOrigin);
    
    [brifView.coverSmallImage sd_setImageWithURL:[NSURL URLWithString:model.coverOrigin] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    [brifView.avatarPathImage sd_setImageWithURL:[NSURL URLWithString:model.coverSmall] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    brifView.nicknameLable.text = model.nickname;
    brifView.tagsLable.text = model.tags;
    if (model.intro == nil) {
        brifView.introLable.text = @"暂无简介";
    } else {
        brifView.introLable.text = model.intro;
    }
    
    self.navigationItem.title = model.title;
    [brifView.button addTarget:self action:@selector(brifButton) forControlEvents:(UIControlEventTouchUpInside)];
    return brifView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kScreenHeight / 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"播放声音";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    KLSGPlayRadioViewController *playViewController = (KLSGPlayRadioViewController *)appDelegate.playVC;
    // 根据位置得到model
    //    NSArray *array = [self.dataDic valueForKey:@"list"];
    //    KLSGBrifAndVoiceModel *model = array[indexPath.row];
    // 电台标题
    playViewController.rname = self.albumModel.title;
    // radioModel数组
    playViewController.radioModelArray = self.lists;
    // 获取当前点击下标
    playViewController.index = indexPath.row;
    // id
    playViewController.radioId = [self.lists[indexPath.row] trackId];
    playViewController.albumModel = self.lists[indexPath.row];
    playViewController.type = VoiceTypeGeneral;
    [self presentViewController:playViewController animated:YES completion:nil];
}

- (void)addData
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?albumId=%@&isAsc=true&device=android&pageSize=20", self.albumIdString, (long)self.pageId,self.albumIdString];
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    __block KLSGBrifAndVoiceViewController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data != nil) {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.brifModel = [[KLSGBrifAndVoiceModel alloc] init];
            [self.brifModel setValuesForKeysWithDictionary:dictionary];
            self.albumModel = [[KLSGAlbumDetailModel alloc] init];
            [self.albumModel setValuesForKeysWithDictionary:dictionary[@"album"]];
            self.tracksModel = [[KLSGTracksModel alloc] init];
            [self.tracksModel setValuesForKeysWithDictionary:dictionary[@"tracks"]];
            for (NSDictionary *dic in dictionary[@"tracks"][@"list"]) {
                KLSGListModel *model = [[KLSGListModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.lists addObject:model];
                
            }
            
            //            NSDictionary *albumDic = [dictionary valueForKey:@"album"];
            //            KLSGBrifAndVoiceModel *albumModel = [[KLSGBrifAndVoiceModel alloc] init];
            //            [albumModel setValuesForKeysWithDictionary:albumDic];
            //            [self.dataDic setValue:albumModel forKey:@"album"];
            //
            //            NSDictionary *tracksDic = [dictionary valueForKey:@"tracks"];
            //            NSMutableArray *tempArray = [NSMutableArray array];
            //            NSArray *listArray = [tracksDic valueForKey:@"list"];
            //            for (NSDictionary *dic in listArray) {
            //                KLSGBrifAndVoiceModel *model = [[KLSGBrifAndVoiceModel alloc] init];
            //                [model setValuesForKeysWithDictionary:dic];
            //                [tempArray addObject:model];
            //            }
            //            [mySelf.dataDic setValue:tempArray forKey:@"list"];
            //
            [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:mySelf.tableView waitUntilDone:NO];
        } else {
            NSLog(@"解析失败");
            [mySelf performSelectorOnMainThread:@selector(failedLoad) withObject:nil waitUntilDone:NO];
        }
    }];
    [task resume];
}

- (NSMutableArray *)lists
{
    if (!_lists) {
        _lists = [NSMutableArray array];
    }
    return _lists;

}

- (void)failedLoad
{
    self.fail = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, 150, kScreenWidth, kScreenHeight)];
    [self.fail netRequestFailWithBlock:^{
        [self.fail hidden];
        [self addData];
    }];
    [self.tableView addSubview:self.fail];
}

- (void)reloadData:(UITableView *)tableView
{
//    [self addHeaderView];
    [tableView reloadData];
}

- (void)brifButton
{
    KLSGSpeakBrifController *brifC = [[KLSGSpeakBrifController alloc] init];
    brifC.modalTransitionStyle = UIModalPresentationCurrentContext;
    brifC.model = self.albumModel;
    [self presentViewController:brifC animated:YES completion:nil];
}

@end
